from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import urlfetch
import logging
import time

class Photo(db.Model):
	title = db.StringProperty()
	medium_size_image = db.BlobProperty()
	small_size_image = db.BlobProperty()

def saveImage(url):
	return saveImageTry(url,1)

def saveImageTry(url, try_num):
	q = db.GqlQuery("SELECT * FROM Photo WHERE title = :1", url)
	photoList = q.fetch(1)
	if len(photoList) == 0:
		try:
			result = urlfetch.fetch(url=url, follow_redirects = False)
			if result.status_code == 200:
				photo = Photo()
				photo.title = url
				img = images.Image(db.Blob(result.content))
				img.im_feeling_lucky()
				img.resize(width = 400, height = int(img.height * 400 / img.width))
				photo.medium_size_image = db.Blob(img.execute_transforms(output_encoding=images.PNG))
				img.resize(width = 100, height = int(img.height * 100 / img.width))
				img.im_feeling_lucky()
				photo.small_size_image = db.Blob(img.execute_transforms(output_encoding=images.PNG))
				photo.put()
				return True
			else:
				raise urlfetch.Error()
		except urlfetch.Error:
			time.sleep(1)
			if try_num <= 3:
				return saveImageTry(url, try_num + 1)
			else:
				logging.error('Image url %s cannot connect', url)
				return False
	else:
		return True
